<?php
class LinkControl extends Control{
	
	public function __construct(){
		parent::__construct();
		
		//子菜单
		$submenu = array(
			array(
				'alias' => 'linkList',
				'title' => '网址列表',
				'url'	=> C('site_admin') . 'index.php?a=menu&m=linkList',
			),
			array(
				'alias' => 'addLink',
				'title' => '添加网址',
				'url'	=> C('site_admin') . 'index.php?a=menu&m=addLink',
			),
			array(
				'alias' => 'editLink',
				'title' => '编辑网址',
				'url'	=> C('site_admin') . 'index.php?a=menu&m=editLink',
			),
		);
		
		$this->assign('mainMenu','link');
		$this->assign('submenu',$submenu);
	}
	
	public function index(){
		$this->linkList();
	}
	
	/**
	 * 新加网址
	 */
	public function addLink($type='add'){
		if($_POST['dosubmit'] == 1){
			//新加 or 编辑
			$data['cid'] = (int)$_POST['link_cid'];
			$data['id'] = (int)$_POST['link_id'];
			$data['name'] = trim($_POST['link_name']);
			$data['url'] = trim($_POST['link_url']);
			$data['description'] = trim($_POST['link_desc']);
			
			if($data['name'] == ''){
				$url = C('site_url').'index.php?c=link&m=addLink';
				$msg = '网址名称不能为空...';
				redirect($url,3,$msg);
			}
			
			if(empty($data['id'])){
				$result = M('Link')->addLink($data);
			}else{
				$result = M('Link')->editLink($data);
			}
			
			$url = C('site_url').'index.php?c=link&m=linkList';
			$msg = '操作'.($result ? '成功' : '失败').'...';
			$msg = iconv('utf-8','gbk',$msg);
			redirect($url,3,$msg);
		}else{
			//展示表单
			$link_id = (int)$_GET['link_id'];
			if($link_id){
				$link = M('Link')->getLinkById($link_id);
			}

			//分类列表
			$categories = M('Category')->getCategories();

			if($type == 'edit'){
				$this->assign('subMenu','editLink');
			}else{
				$this->assign('subMenu','addLink');
			}
			$this->assign('type',$type);
			$this->assign('categories',$categories);
			$this->assign('link',$link);
			$this->assign('link_id',$link_id);
			$this->assign('formToken',token());
			$this->display('add_link');
		}
	}
	
	/**
	 * 删除网址
	 * @return json
	 */
	public function delLink(){
		$id = (int)$_POST['id'];
		$result = M('Link')->delLink($id);
		$info = '删除'.($result ?  '成功' : '失败');
		$status = (int)$result;
		ajaxReturn('',$info,$status);
	}
	
	/**
	 * 编辑网址
	 */
	public function editLink(){
		$this->addLink('edit');
	}

	/**
	 * 网址列表
	 */
	public function linkList(){
		$links = M('Link')->linkList();
		$this->assign('subMenu','linkList');
		$this->assign('links',$links);
		$this->display('link_list');
	}
}
?>